# !/usr/bin/env python
# encoding: utf-8
# @File    : process_data_module.py
# @Time    : 2021/2/13
# @Author  : qiaowei
# @Version : 1.0
# @Email   : weiweiqiao@126.com
# @License : (C) Copyright 2013-2021
# @Brief   :


from PySide2.QtCore import QThread
from PySide2.QtCore import QObject
from PySide2.QtCore import Qt
from PySide2.QtCore import QFile
from PySide2.QtCore import QTextStream
from PySide2.QtCore import QIODevice
from PySide2.QtCore import Slot
from data_module.track_data_integrated_module import TrackData


class TrackDataProcessing(QObject):
    def __init__(self):
        super(TrackDataProcessing, self).__init__()

    @Slot(list)
    def split_data_to_different_file(self, files_name_with_path: list):
        """
        根据传入的文件名列表，依次读取文件内容，将读取到的数据判别后保存到不同文件中

        :param files_name_with_path: 文件名列表
        :return: None

        """
        # 依次遍历所有选择要处理的文件
        for file_name in files_name_with_path:
            file = QFile(file_name)
            # 创建保存数据的文件
            out_file_process = QFile(file_name.replace('.log', '_PROCESS_.log'))
            out_file_message = QFile(file_name.replace('.log', '_MESSAGE_.log'))

            # 将文件按以只写模式打开
            try:
                # 以下2个if分别判断文件不存在，文件只读形式，如有异常，直接返回。注意两个判断不能合并，会导致
                # 文件直接到结束标志位，后续无法读取文件
                if not file.exists():
                    return
                if not file.open(QIODevice.ReadOnly | QIODevice.Text):
                    return

                in_stream = QTextStream(file)
                # in_stream.setCodec('utf-8')
                in_stream.setAutoDetectUnicode(True)

                # 文件以只写，擦除原内容方式打开
                if out_file_message.open(QFile.WriteOnly | QFile.Truncate) and \
                        out_file_process.open(QFile.WriteOnly | QFile.Truncate):
                    out_stream_process = QTextStream(out_file_process)
                    out_stream_message = QTextStream(out_file_message)

                    # 按行读取文件内容，按要求保存到不同文件中
                    while not in_stream.atEnd():
                        content = in_stream.readLine()
                        if 'sysRecv 1 received message' in content:
                            out_stream_message << content.replace('sysRecv 1 received message', '')\
                                << '\n'
                        elif 'sysRecv 1 process' in content:
                            out_stream_process << content.replace('sysRecv 1 process', '') << '\n'

            except IOError as io_err:
                print('File error:' + str(io_err))
            finally:
                if file.isOpen():
                    file.close()
                if out_file_process.isOpen():
                    out_file_process.close()
                if out_file_message.isOpen():
                    out_file_message.close()

